
/**
 * 用户收藏集管理模块
 * 支持国际化的新架构
 */
const {
	userCollectionCollection,
	patternCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')
const {
	getUserId
} = require('../../common/utils')

module.exports = {
	/**
	 * 获取用户收藏集列表
	 * @param {object} params 查询参数
	 * @returns {object} 收藏集列表
	 */
	async getCollectionList(params = {}) {
		try {
			const userId = await getUserId(this)
			const { page = 1, limit = 20 } = params
			
			// 获取收藏集列表
			const collectionResult = await userCollectionCollection.where({
				user_id: userId
			})
			.orderBy('sort_order', 'asc')
			.orderBy('create_time', 'desc')
			.skip((page - 1) * limit)
			.limit(limit)
			.get()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 转换数据格式（收藏集名称不需要多语言转换）
			const transformedData = collectionResult.data.map(item => {
				// 计算图案数量
				const patternCount = item.patterns ? item.patterns.length : 0
				
				return {
					id: item._id,
					collection_name: item.collection_name,
					description: item.description,
					cover_image: item.cover_image,
					background_color: item.background_color,
					pattern_count: patternCount,
					is_default: item.is_default,
					sort_order: item.sort_order,
					create_time: item.create_time,
					update_time: item.update_time
				}
			})

			// 获取总数
			const totalResult = await userCollectionCollection.where({
				user_id: userId
			}).count()

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.list.success') : '获取成功',
				data: {
					list: transformedData,
					total: totalResult.total,
					page,
					limit,
					totalPages: Math.ceil(totalResult.total / limit)
				}
			}
		} catch (error) {
			console.error('[sh_user_collection] getCollectionList error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.list.failed') : '获取收藏集列表失败'
			}
		}
	},

	/**
	 * 创建收藏集
	 * @param {object} params 创建参数
	 * @returns {object} 创建结果
	 */
	async createCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_name, description, cover_image, background_color } = params

			if (!collection_name || !collection_name.trim()) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.name.required') : '收藏集名称不能为空'
				}
			}

			// 检查收藏集名称是否重复
			const existCollection = await userCollectionCollection.where({
				user_id: userId,
				collection_name: collection_name.trim()
			}).get()

			if (existCollection.data.length > 0) {
				throw {
					errCode: ERROR.COLLECTION_EXISTS,
					errMsg: this.t ? this.t('collection.name.exists') : '收藏集名称已存在'
				}
			}

			// 获取当前收藏集数量作为排序依据
			const countResult = await userCollectionCollection.where({
				user_id: userId
			}).count()

			// 创建收藏集数据对象
			const collectionData = {
				user_id: userId,
				collection_name: collection_name.trim(),
				description: description || '',
				cover_image: cover_image || '',
				background_color: background_color || '',
				patterns: [],
				is_default: false,
				sort_order: countResult.total,
				create_time: new Date(),
				update_time: new Date()
			}

			// 创建收藏集
			const collectionResult = await userCollectionCollection.add(collectionData)

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.create.success') : '创建成功',
				data: {
					collection_id: collectionResult.id,
					...collectionData
				}
			}
		} catch (error) {
			console.error('[sh_user_collection] createCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.create.failed') : '创建收藏集失败'
			}
		}
	},

	/**
	 * 更新收藏集信息
	 * @param {object} params 更新参数
	 * @returns {object} 更新结果
	 */
	async updateCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id, collection_name, description, cover_image, background_color } = params

			if (!collection_id) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.id.required') : '收藏集ID不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			// 构建更新数据
			const updateData = {
				update_time: new Date()
			}

			if (collection_name !== undefined) {
				if (!collection_name.trim()) {
					throw {
						errCode: ERROR.PARAM_ERROR,
						errMsg: this.t ? this.t('collection.name.required') : '收藏集名称不能为空'
					}
				}

				// 检查名称是否重复
				const existCollection = await userCollectionCollection.where({
					user_id: userId,
					collection_name: collection_name.trim(),
					_id: dbCmd.neq(collection_id)
				}).get()

				if (existCollection.data.length > 0) {
					throw {
						errCode: ERROR.COLLECTION_EXISTS,
						errMsg: this.t ? this.t('collection.name.exists') : '收藏集名称已存在'
					}
				}

				updateData.collection_name = collection_name.trim()
			}

			if (description !== undefined) {
				updateData.description = description
			}

			if (cover_image !== undefined) {
				updateData.cover_image = cover_image
			}

			if (background_color !== undefined) {
				updateData.background_color = background_color
			}

			// 更新收藏集
			await userCollectionCollection.doc(collection_id).update(updateData)

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.update.success') : '更新成功'
			}
		} catch (error) {
			console.error('[sh_user_collection] updateCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.update.failed') : '更新收藏集失败'
			}
		}
	},

	/**
	 * 删除收藏集
	 * @param {object} params 删除参数
	 * @returns {object} 删除结果
	 */
	async deleteCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id } = params

			if (!collection_id) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.id.required') : '收藏集ID不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0]
			
			// 不能删除默认收藏集
			if (collection.is_default) {
				throw {
					errCode: ERROR.CANNOT_DELETE_DEFAULT,
					errMsg: this.t ? this.t('collection.cannot.delete.default') : '不能删除默认收藏集'
				}
			}

			// 删除收藏集
			await userCollectionCollection.doc(collection_id).remove()

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.delete.success') : '删除成功'
			}
		} catch (error) {
			console.error('[sh_user_collection] deleteCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.delete.failed') : '删除收藏集失败'
			}
		}
	},

	/**
	 * 获取收藏集详情
	 * @param {object} params 查询参数
	 * @returns {object} 收藏集详情
	 */
	async getCollectionDetail(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id } = params

			if (!collection_id) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.id.required') : '收藏集ID不能为空'
				}
			}

			// 获取收藏集详情
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			let collection = collectionResult.data[0]
			
			// 获取图案详细信息
			let patterns = []
			if (collection.patterns && collection.patterns.length > 0) {
				const patternIds = collection.patterns.map(p => p.pattern_id)
				
				const patternResult = await patternCollection.where({
					_id: dbCmd.in(patternIds)
				}).get()
				
				// 获取当前请求的语言
				const language = this.language || 'zh-Hans'
				
				// 合并图案信息和收藏时间，按排序顺序排列
				patterns = collection.patterns.map(collectionPattern => {
					const patternInfo = patternResult.data.find(p => p._id === collectionPattern.pattern_id)
					
					if (!patternInfo) return null
					
					// 转换多语言数据
					const transformedPattern = transformMultiLangData([patternInfo], language, {
						multiLangFields: ['pattern_name', 'description'],
						keepFields: [
							'category', 'tags', 'preview_image', 'thumbnail', 'duration', 'play_time',
							'create_time', 'update_time'
						],
						idMapping: { '_id': 'id' }
					})[0]
					
					return {
						...transformedPattern,
						sort_order: collectionPattern.sort_order || 0,
						add_time: collectionPattern.add_time
					}
				})
				.filter(Boolean) // 过滤掉不存在的图案
				.sort((a, b) => a.sort_order - b.sort_order) // 按排序顺序排列
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.detail.success') : '获取成功',
				data: {
					id: collection._id,
					collection_name: collection.collection_name,
					description: collection.description,
					cover_image: collection.cover_image,
					background_color: collection.background_color,
					pattern_count: patterns.length,
					is_default: collection.is_default,
					sort_order: collection.sort_order,
					create_time: collection.create_time,
					update_time: collection.update_time,
					patterns: patterns
				}
			}
		} catch (error) {
			console.error('[sh_user_collection] getCollectionDetail error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.detail.failed') : '获取收藏集详情失败'
			}
		}
	},

	/**
	 * 添加图案到收藏集
	 * @param {object} params 添加参数
	 * @returns {object} 添加结果
	 */
	async addPatternToCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id, pattern_id } = params

			if (!collection_id || !pattern_id) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.pattern.required') : '收藏集ID和图案ID不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			// 检查图案是否存在
			const patternResult = await patternCollection.doc(pattern_id).get()
			if (patternResult.data.length === 0) {
				throw {
					errCode: ERROR.PATTERN_NOT_FOUND,
					errMsg: this.t ? this.t('pattern.not.found') : '图案不存在'
				}
			}

			const collection = collectionResult.data[0]
			const patterns = collection.patterns || []
			
			// 检查是否已在该收藏集中
			const existingPattern = patterns.find(p => p.pattern_id === pattern_id)
			if (existingPattern) {
				throw {
					errCode: ERROR.PATTERN_EXISTS,
					errMsg: this.t ? this.t('pattern.already.in.collection') : '图案已在该收藏集中'
				}
			}

			// 添加图案到收藏集
			const maxSortOrder = patterns.length > 0 ? Math.max(...patterns.map(p => p.sort_order || 0)) : 0
			const newPattern = {
				pattern_id: pattern_id,
				sort_order: maxSortOrder + 1,
				add_time: new Date()
			}
			
			await userCollectionCollection.doc(collection_id).update({
				patterns: dbCmd.push(newPattern),
				update_time: new Date()
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.pattern.add.success') : '添加成功'
			}
		} catch (error) {
			console.error('[sh_user_collection] addPatternToCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.pattern.add.failed') : '添加图案到收藏集失败'
			}
		}
	},

	/**
	 * 从收藏集移除图案
	 * @param {object} params 移除参数
	 * @returns {object} 移除结果
	 */
	async removePatternFromCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id, pattern_id } = params

			if (!collection_id || !pattern_id) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.pattern.required') : '收藏集ID和图案ID不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0]
			const patterns = collection.patterns || []
			
			// 检查图案是否在该收藏集中
			const patternIndex = patterns.findIndex(p => p.pattern_id === pattern_id)
			if (patternIndex === -1) {
				throw {
					errCode: ERROR.PATTERN_NOT_FOUND,
					errMsg: this.t ? this.t('pattern.not.in.collection') : '图案不在该收藏集中'
				}
			}

			// 从收藏集移除图案
			const updatedPatterns = patterns.filter(p => p.pattern_id !== pattern_id)
			
			await userCollectionCollection.doc(collection_id).update({
				patterns: updatedPatterns,
				update_time: new Date()
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.pattern.remove.success') : '移除成功'
			}
		} catch (error) {
			console.error('[sh_user_collection] removePatternFromCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.pattern.remove.failed') : '从收藏集移除图案失败'
			}
		}
	},

	/**
	 * 批量从收藏集移除图案
	 * @param {object} params 批量移除参数
	 * @param {string} params.collection_id 收藏集ID
	 * @param {array} params.pattern_ids 图案ID数组
	 * @returns {object} 批量移除结果
	 */
	async batchRemovePatternsFromCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id, pattern_ids } = params

			if (!collection_id || !pattern_ids || !Array.isArray(pattern_ids) || pattern_ids.length === 0) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.batch.params.required') : '收藏集ID和图案ID数组不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0]
			const patterns = collection.patterns || []
			
			// 统计移除结果
			const removedPatterns = []
			const notFoundPatterns = []
			
			// 过滤出要移除的图案和不存在的图案
			pattern_ids.forEach(pattern_id => {
				const patternIndex = patterns.findIndex(p => p.pattern_id === pattern_id)
				if (patternIndex !== -1) {
					removedPatterns.push(patterns[patternIndex])
				} else {
					notFoundPatterns.push(pattern_id)
				}
			})

			// 移除图案
			const updatedPatterns = patterns.filter(p => !pattern_ids.includes(p.pattern_id))
			
			await userCollectionCollection.doc(collection_id).update({
				patterns: updatedPatterns,
				update_time: new Date()
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.batch.remove.success') : '批量移除成功',
				data: {
					removed_count: removedPatterns.length,
					not_found_count: notFoundPatterns.length,
					removed_patterns: removedPatterns,
					not_found_patterns: notFoundPatterns,
					total_patterns: updatedPatterns.length
				}
			}
		} catch (error) {
			console.error('[sh_user_collection] batchRemovePatternsFromCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.batch.remove.failed') : '批量移除图案失败'
			}
		}
	},

	/**
	 * 重新排序收藏集中的图案
	 * @param {object} params 排序参数
	 * @returns {object} 排序结果
	 */
	async reorderPatternsInCollection(params = {}) {
		try {
			const userId = await getUserId(this)
			const { collection_id, pattern_orders } = params

			if (!collection_id || !Array.isArray(pattern_orders)) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.reorder.invalid') : '收藏集ID和图案排序数组不能为空'
				}
			}

			// 检查收藏集权限
			const collectionResult = await userCollectionCollection.where({
				_id: collection_id,
				user_id: userId
			}).get()

			if (collectionResult.data.length === 0) {
				throw {
					errCode: ERROR.COLLECTION_NOT_FOUND,
					errMsg: this.t ? this.t('collection.not.found') : '收藏集不存在或无权限'
				}
			}

			const collection = collectionResult.data[0]
			const patterns = collection.patterns || []
			
			// 更新图案的排序顺序
			const updatedPatterns = patterns.map(pattern => {
				const orderInfo = pattern_orders.find(order => order.pattern_id === pattern.pattern_id)
				if (orderInfo) {
					return {
						...pattern,
						sort_order: orderInfo.sort_order
					}
				}
				return pattern
			})
			
			await userCollectionCollection.doc(collection_id).update({
				patterns: updatedPatterns,
				update_time: new Date()
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.reorder.success') : '排序成功'
			}
		} catch (error) {
			console.error('[sh_user_collection] reorderPatternsInCollection error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.reorder.failed') : '重新排序收藏集图案失败'
			}
		}
	},

	/**
	 * 批量查询多个图案的收藏状态
	 * @param {object} params 查询参数
	 * @param {array} params.pattern_ids 图案ID数组
	 * @returns {object} 图案收藏状态映射表
	 */
	async batchGetPatternsCollectionStatus(params = {}) {
		try {
			const userId = await getUserId(this)
			const { pattern_ids } = params

			if (!pattern_ids || !Array.isArray(pattern_ids) || pattern_ids.length === 0) {
				throw {
					errCode: ERROR.PARAM_ERROR,
					errMsg: this.t ? this.t('collection.pattern_ids.required') : '图案ID数组不能为空'
				}
			}

			// 查询用户所有包含这些图案的收藏册
			const collectionResult = await userCollectionCollection.where({
				user_id: userId,
				'patterns.pattern_id': dbCmd.in(pattern_ids)
			}).get()

			// 构建图案收藏状态映射表
			const patternStatusMap = {}
			
			// 初始化所有图案为未收藏状态
			pattern_ids.forEach(patternId => {
				patternStatusMap[patternId] = {
					is_collected: false,
					collection_ids: []
				}
			})

			// 遍历收藏册,标记已收藏的图案
			collectionResult.data.forEach(collection => {
				if (collection.patterns && collection.patterns.length > 0) {
					collection.patterns.forEach(pattern => {
						if (pattern_ids.includes(pattern.pattern_id)) {
							patternStatusMap[pattern.pattern_id].is_collected = true
							patternStatusMap[pattern.pattern_id].collection_ids.push(collection._id)
						}
					})
				}
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.batch-status.success') : '查询成功',
				data: patternStatusMap
			}
		} catch (error) {
			console.error('[sh_user_collection] batchGetPatternsCollectionStatus error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.batch-status.failed') : '批量查询图案收藏状态失败'
			}
		}
	},

	/**
	 * 根据图案ID获取包含该图案的收藏册列表
	 * @param {object} params 查询参数
	 * @param {string} params.pattern_id 图案ID
	 * @returns {object} 包含该图案的收藏册列表
	 */
	async getCollectionsByPattern(params = {}) {
		try {
			const userId = await getUserId(this)
			const { pattern_id } = params

			if (!pattern_id) {
				throw {
					errCode: ERROR.PARAM_REQUIRED,
					errMsgValue: { param: 'pattern_id' }
				}
			}

			// 查询包含指定图案的收藏册
			const collectionResult = await userCollectionCollection.where({
				user_id: userId,
				'patterns.pattern_id': pattern_id
			})
			.orderBy('sort_order', 'asc')
			.orderBy('create_time', 'desc')
			.get()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 转换数据格式
			const transformedData = collectionResult.data.map(item => {
				// 计算图案数量
				const patternCount = item.patterns ? item.patterns.length : 0
				
				// 查找当前图案在收藏册中的位置
				const patternInCollection = item.patterns ? 
					item.patterns.find(p => p.pattern_id === pattern_id) : null

				return {
					id: item._id,
					collection_name: item.collection_name,
					description: item.description,
					cover_image: item.cover_image,
					background_color: item.background_color,
					pattern_count: patternCount,
					sort_order: item.sort_order,
					is_default: item.is_default || false,
					create_time: item.create_time,
					update_time: item.update_time,
					// 图案在该收藏册中的排序位置
					pattern_sort_order: patternInCollection ? patternInCollection.sort_order : 0
				}
			})

			return {
				errCode: 0,
				errMsg: this.t ? this.t('collection.pattern-collections.success') : '获取成功',
				data: transformedData
			}
		} catch (error) {
			console.error('[sh_user_collection] getCollectionsByPattern error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('collection.pattern-collections.failed') : '获取包含该图案的收藏册列表失败'
			}
		}
	}
}
